package com.snowsea.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snowsea.mapper.OrderMapper;
import com.snowsea.enums.OrderEnums;
import com.snowsea.pojo.Order;
import com.snowsea.service.OrderService;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


/**
 * @className: OrderServiceImpl
 * @auther: Jerry
 * @date: 2021/4/19 17:29
 * @desctiption: TODO
 * @version: 1.0
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void pay(Order order) {
        String orderRequest = JSON.toJSONString(order);
        Message message = MessageBuilder.withPayload(orderRequest).build();
        try {
            TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction(
                    "myTransactionGroup",
                    "orderPaySuccessTopic",
                    message,
                    null);
            System.out.println(sendResult);
        } catch (MessagingException e) {
            e.printStackTrace();
            // 发生异常，状态变更为“已退款”
            this.updateOrderState(order.getId(), OrderEnums.REFUND.getCode());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOrderState(Long orderId, String orderState) {
        Order order = new Order();
        order.setId(orderId);
        order.setOrderState(orderState);
        order.setGmtModified(new Date());
        return this.baseMapper.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(Order order) {
        order.setGmtCreate(new Date());
        order.setGmtModified(new Date());
        this.baseMapper.insert(order);
    }
}
